package com.scidpro;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

/**
 * based on SelectFileActivity
 * 
 */
public class MyBooksListActivity extends Activity {

	public class MyBooksListAdapter extends ArrayAdapter<String> {

		public MyBooksListAdapter(Context context) {
			super(context, android.R.layout.simple_list_item_1);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO: clean this up, call to super should not be necessary
			View view = super.getView(position, convertView, parent);
			String item = this.getItem(position);
			if (item != null) {
				String name = new File(item).getName();
				if (name.endsWith(extension)) {
					name = name.substring(0, name.indexOf(extension));
				}

				if (view instanceof TextView) {
					((TextView) view).setText(name);
				}
			}
			return view;
		}
	}

	public static final String PARENT_FOLDER = ".. (parent folder)";
	private static Stack<String> path = new Stack<String>();
	private MyBooksListAdapter adapter;
	private String extension;
	private int defaultItem = 0;

	private ListView list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		list = new ListView(this);
		setContentView(list);

		extension = ".si4";

		path = getStringStackPref(this, "lastPath");
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		defaultItem = settings.getInt("lastPathDefaultItem", 0);
		File scidFileDir = new File(Environment.getExternalStorageDirectory() + File.separator + ScidAndroidActivity.SCID_DIRECTORY);
		if (!scidFileDir.exists()) {
			scidFileDir.mkdirs();
		}
		showList();

		registerForContextMenu(list);
	}

	protected void showList() {
		adapter = new MyBooksListAdapter(this);
		list.setAdapter(adapter);
		List<String> fileNames = changePath();
		if (path.size() == 0 && fileNames.size() == 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.app_name).setMessage(R.string.no_scid_files);
			builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					setResult(Activity.RESULT_CANCELED);
					finish();
					return;
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
		}
		list.setSelectionFromTop(defaultItem, 0);
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
				onSelectBook(pos);
			}
		});
	}

	private void setStringStackPref(Context context, String key, Stack<String> values) {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		SharedPreferences.Editor editor = prefs.edit();
		JSONArray a = new JSONArray();
		for (int i = 0; i < values.size(); i++) {
			a.put(values.get(i));
		}
		if (!values.isEmpty()) {
			editor.putString(key, a.toString());
		} else {
			editor.putString(key, null);
		}
		editor.commit();
	}

	private String getFullPath() {
		String pathName;
		if (path.size() > 0) {
			pathName = path.lastElement();
		} else {
			pathName = Environment.getExternalStorageDirectory() + File.separator + ScidAndroidActivity.SCID_DIRECTORY + File.separator;
		}
		return pathName;
	}

	private List<String> findFilesInDirectory(String dirName, final String extension) {
		File dir = new File(dirName);
		File[] files = dir.listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				return pathname.isFile() && ((pathname.getAbsolutePath().endsWith(extension)) || extension.equals("*"));
			}
		});
		if (files == null) {
			files = new File[0];
		}
		File[] dirs = dir.listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				return pathname.isDirectory();
			}
		});
		if (dirs == null) {
			dirs = new File[0];
		}
		String[] fileNames = new String[files.length];
		for (int i = 0; i < files.length; i++) {
			fileNames[i] = files[i].getAbsolutePath();
		}
		String[] dirNames = new String[dirs.length];
		for (int i = 0; i < dirs.length; i++) {
			dirNames[i] = dirs[i].getAbsolutePath();
		}
		Arrays.sort(dirNames, String.CASE_INSENSITIVE_ORDER);
		Arrays.sort(fileNames, String.CASE_INSENSITIVE_ORDER);
		List<String> resultList = new ArrayList<String>(Arrays.asList(dirNames));
		resultList.addAll(Arrays.asList(fileNames));
		return resultList;
	}

	private List<String> changePath() {
		adapter.clear();
		List<String> newFileNames = findFilesInDirectory(getFullPath(), this.extension);
		if (path.size() > 0) {
			adapter.add(PARENT_FOLDER);
		}
		for (String fileName : newFileNames) {
			adapter.add(fileName);
		}
		return newFileNames;
	}

	private Stack<String> getStringStackPref(Context context, String key) {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		String json = prefs.getString(key, null);
		Stack<String> result = new Stack<String>();
		if (json != null) {
			try {
				JSONArray a = new JSONArray(json);
				for (int i = 0; i < a.length(); i++) {
					String url = a.optString(i);
					result.add(url);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		getMenuInflater().inflate(R.menu.my_books_list_context_menu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

		switch (item.getItemId()) {
		case R.id.select_book_item: {
			onSelectBook(info.position);
			break;
		}
		case R.id.delete_book_item: {
			onDeleteBook(info.position);
			break;
		}
		}
		return true;
	}

	private void onSelectBook(int position) {
		if (position >= 0 && position < adapter.getCount()) {
			String item = adapter.getItem(position);
			if (path.size() > 0 && item.equals(PARENT_FOLDER)) {
				MyBooksListActivity.path.pop();
				changePath();
				return;
			}
			defaultItem = position;
			File itemFile = new File(item);
			if (itemFile.isDirectory()) {
				path.add(item);
				changePath();
			} else {
				setResult(Activity.RESULT_OK, (new Intent()).setAction(item));
				SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MyBooksListActivity.this);
				Editor editor = settings.edit();
				editor.putInt("lastPathDefaultItem", defaultItem);
				editor.commit();
				setStringStackPref(MyBooksListActivity.this, "lastPath", path);
				finish();
			}
		}
	}

	private void onDeleteBook(int position) {
		String filename = adapter.getItem(position);

		if (filename.endsWith(extension)) {
			filename = filename.substring(0, filename.indexOf(extension));
		}

		File si4File = new File(filename + ".si4");
		File sg4File = new File(filename + ".sg4");
		File sn4File = new File(filename + ".sn4");
		File pgnFile = new File(filename + ".pgn");

		if (si4File.exists()) {
			si4File.delete();
		}
		if (sg4File.exists()) {
			sg4File.delete();
		}
		if (sn4File.exists()) {
			sn4File.delete();
		}
		if (pgnFile.exists()) {
			pgnFile.delete();
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.app_name);
		builder.setMessage("Book deleted");
		builder.setPositiveButton(R.string.ok, null);
		AlertDialog alert = builder.create();
		alert.show();
		
		showList();
	}

}
